#include <windows.h>
#include <winsock.h>

#include <process.h>
#include <stdio.h>

#include "wcserver.h"
#pragma hdrstop

void EchoHandler(void *p)
//  Receive and process all incoming requests on a single socket. Respond
//  by uppercasing all inbound data and returning to the client.
{
  SOCKET s = (SOCKET)p;
  while (1) {
    char buf[1024];
    int n = recv(s, buf, sizeof(buf), 0);
    if (n <= 0) {
      break;
    }
    for (int i = 0; i < n; i++) {
      buf[i] = toupper(buf[i]);
    }
    printf("%s", buf);
    send(s, buf, n, 0);
  }
  closesocket(s);
}

int main(int, char *[])
{
  // Connect to the default wildcat server

  if (!WildcatServerConnect(NULL)) {
    return 1;
  }
  if (!WildcatServerCreateContext()) {
    return 1;
  }

  // Initialize and load WinSock

  WSAData wsaData;
  WSAStartup(MAKEWORD(1, 1), &wsaData);
  SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
  sockaddr_in sin;
  sin.sin_family = PF_INET;
  sin.sin_addr.s_addr = INADDR_ANY;
  sin.sin_port = 0;
  bind(s, (sockaddr *)&sin, sizeof(sin));
  int n = sizeof(sin);
  getsockname(s, (sockaddr *)&sin, &n);

  // Register service with Wildcat!

  TWildcatService service;
  ZeroMemory(&service, sizeof(service));
  strcpy(service.Name, "Echo");
  strcpy(service.Vendor, "Santronics Software, Inc.");
  service.Version = 1;
  service.Port = ntohs(sin.sin_port);
  RegisterService(service);

  // Listen for incoming requests

  printf("Echo service active on %s/%d\n", inet_ntoa(*(struct in_addr *)&service.Address), ntohs(sin.sin_port));
  listen(s, 5);
  while (1) {
    sockaddr_in tin;
    int n = sizeof(tin);
    SOCKET t = accept(s, (sockaddr *)&tin, &n);
    _beginthread(EchoHandler, 0, (void *)t);
  }
  return 0;
}
